package com.tangye.massageshop.controller;

import com.alibaba.fastjson.JSON;
import com.tangye.massageshop.entity.CompanyEntity;
import com.tangye.massageshop.entity.UserEntity;
import com.tangye.massageshop.exception.ShopException;
import com.tangye.massageshop.service.CompanyService;
import com.tangye.massageshop.service.UserService;
import com.tangye.massageshop.util.Result;
import com.tangye.massageshop.util.ThreadLocalUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@Log4j2
@RestController
@RequestMapping("/company")
public class CompanyController {

    @Resource
    private CompanyService companyService;
    @Resource
    private UserService userService;

    @GetMapping("/getAllCompany")
    public Result<List<CompanyEntity>> getAllCompany() {
        log.info(JSON.toJSONString(ThreadLocalUtil.get()));
        return Result.success(companyService.getAll());
    }


    @PostMapping("/addCompany")
    public Result<UserEntity> addCompany(@Validated CompanyEntity companyEntity) {
        UserEntity userSession = ThreadLocalUtil.get();
        if (!userSession.isAdmin()) {
            throw new ShopException("非超级管理员");
        }
        log.info("addCompany入参：{}", JSON.toJSONString(companyEntity));
        UserEntity userEntity = companyService.addCompany(companyEntity);
        log.info("addCompany反参：{}", JSON.toJSONString(userEntity));
        return Result.success(userEntity);
    }

    @PostMapping("/updateCompany")
    public Result<String> updateCompany(@Validated CompanyEntity companyEntity) {
        UserEntity userEntity = ThreadLocalUtil.get();
        if (!userEntity.isAdmin()) {
            return Result.error("非超级管理员");
        }
        companyService.updateCompany(companyEntity);
        return Result.ok();
    }

}
